//
//  SEGSelectTopicTypeViewModel.m
//  Commom
//
//  Created by 梁学彰 on 2020/6/6.
//

#import "SEGSelectTopicTypeViewModel.h"

@implementation SEGSelectTopicTypeViewModel
#pragma mark - life cycle
- (instancetype)initWithSelectItem:(SEGTopicDataItemModel *)model block:(topicSelectBlock)block {
    if (self = [super init]) {
        self.selectItem = model;
        self.selectBlock = block;
        self.page = 1;
    }
    return self;
}

#pragma mark - init


#pragma mark - send request
/// 获取列表数据
/// @param refresh 是否重新刷新
- (RACSignal *)sendTopicListRequestWithRefresh:(BOOL)refresh {
    if (refresh) {
        self.page = 1;
    }else {
        self.page ++;
    }
    if (self.sHManager.topicDataModel&&self.sHManager.topicDataModel.totalPage.intValue + 1 <= self.page) {
        return nil;
    }
    
    
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        [self.sHManager requestTopicListWithPage:[NSString stringWithFormat:@"%ld",(long)self.page] finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {

            if (!isSuccessed) {
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
            }
            self.model = self.sHManager.topicDataModel;
            if (self.page == 1) {
                [self.dataArray removeAllObjects];
            }
            [self.dataArray addObjectsFromArray:self.model.topicList];
            [subscriber sendCompleted];
        }];
        
        return nil;
    }];
    return signal;
    
}

- (RACSignal *)selectIndex:(NSIndexPath *)index {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        [self.dataArray enumerateObjectsUsingBlock:^(SEGTopicDataItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.isSelect = NO;
        }];
        
        SEGTopicDataItemModel *model = self.dataArray[index.row];
        model.isSelect = YES;
        if (self.selectBlock) {
            self.selectBlock(model);
            [subscriber sendNext:nil];
        }
        [subscriber sendCompleted];
        return nil;
    }];
    return signal;
}

#pragma mark - custom delegate

#pragma mark - system delegate

#pragma mark - event response

#pragma mark - private methods

#pragma mark - setter and getter
- (SEGSHManager*)sHManager {
    if (!_sHManager) {
        _sHManager = [[SEGSHManager alloc] init];
    }
    return _sHManager;
}

- (NSMutableArray<SEGTopicDataItemModel *> *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
@end
